package com.sunyur.tailor.channel.common.middle.util;

import com.sunyur.tailor.channel.common.middle.base.TokenUtilModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 *
 * @Author 99288
 * @Description 令牌加密解密
 * @Date 20:30 2021/8/24
 * @Param
 * @return
**/
public class TokenUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(TokenUtil.class);

    private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder();
    private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder();

    /**
     * 生成 token
     *
     * @param clientId
     * @param clientSecret
     * @param expireTime   过期时间
     * @return
     */
    public static String generateToken(String clientId, String clientSecret, long expireTime) {
        StringBuilder sb = new StringBuilder();
        sb.append(clientId).append('|').append(clientSecret).append('|').append(expireTime);
        try {
            String encrypt = AESUtil.encrypt(sb.toString(), key(clientSecret));
            return BASE64_ENCODER.encodeToString(encrypt.getBytes(StandardCharsets.UTF_8));

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 解密
     *
     * @param token
     * @param clientSecret
     * @return
     */
    public static TokenUtilModel decryptToken(String token, String clientSecret) {

        try {
            byte[] decode = BASE64_DECODER.decode(token);
            String encrypt = AESUtil.decrypt(new String(decode, StandardCharsets.UTF_8), key(clientSecret));
            String[] split = encrypt.split("\\|");
            TokenUtilModel model = new TokenUtilModel();
            model.setClientId(split[0]);
            model.setClientSecret(split[1]);
            model.setExpireTime(Long.parseLong(split[2]));
            return model;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        return null;
    }


    private static String key(String clientSecret) {
        return MD5Util.encryptPassword(clientSecret).substring(0, 16);
    }


}
